package com.ruoyi.framework.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.domain.entity.MesMessage;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.domain.pojo.Message;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.common.utils.webSocket.MessageUtils;
import com.ruoyi.system.service.ISysUserFriendService;
import com.ruoyi.system.service.impl.SysUserFriendServiceImpl;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import net.sf.jsqlparser.expression.LongValue;
import org.apache.catalina.session.StandardSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;


@ServerEndpoint(value = "/websocket" ,configurator = GetHttpSessionConfigurator.class)
@Component
public class WebSocketServer extends TextWebSocketHandler {

    @Autowired
    private void setRedisTemplate(RedisTemplate redisTemplate){
        this.redisTemplate = redisTemplate;
    }

    private RedisTemplate redisTemplate;


    //用来存储每一个客户端对象对应的ChatEndpoint对象
    private static Map<String,WebSocketServer> onlineUsers = new ConcurrentHashMap<>();

    //和某个客户端连接对象，需要通过他来给客户端发送数据
    private Session session;

    //httpSession中存储着当前登录的用户名
    private LoginUser user;
    //你的Service实现类
    SysUserFriendServiceImpl sysUserFriendService = SpringUtils.getBean(SysUserFriendServiceImpl.class);
    SysUserServiceImpl sysUserService = SpringUtils.getBean(SysUserServiceImpl.class);
    @OnOpen
    //连接建立成功调用
    public void onOpen(Session session, EndpointConfig config) {
        //需要通知其他的客户端，将所有的用户的用户名发送给客户端
        this.session = session;
        //获取HttpSession对象
         user = (LoginUser)config.getUserProperties().get("user");
        //获取用户名
        //存储该链接对象
        onlineUsers.put(user.getUsername(),this);


        //获取需要推送的消息
        String message = com.ruoyi.common.utils.webSocket.MessageUtils.getMessage(true, null, new Message());
        //广播给所有的用户
        broadcastAllUsers(message);
    }


    private void broadcastAllUsers(String message) {
        try {
            //遍历 onlineUsers 集合
            Set<String> names = onlineUsers.keySet();
            for (String name : names) {
                //获取该用户对应的ChatEndpoint对象
                WebSocketServer webSocketServer = onlineUsers.get(name);
                //发送消息
                webSocketServer.session.getBasicRemote().sendText(message);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Set<String> getNames() {
        return onlineUsers.keySet();
    }

    @OnMessage
    public void onMessage(Session session, String message) throws IOException {
        //获取客户端发送来的数据 {"toName":"张三","message":"你好"}

        ObjectMapper mapper =new ObjectMapper();
        Message mess = mapper.readValue(message, Message.class);
        System.out.println("收到消息: " + mess);

        //  要推送的消息
        String data = MessageUtils.getMessage(false, user.getUsername(), mess);
        //查询该用户是否在线
        WebSocketServer webSocketServer = onlineUsers.get(mess.getToName());
        if(webSocketServer==null){
            //用户不在线 将数据存储在数据库 标记为未读
            sysUserFriendService.insertHistory(new MesMessage(0, user.getUserId().intValue(), mess.getSendId(), mess.getMessage(), 0, null));
        }else {
            //用户在线 发送给用户 将数据存储在数据库 标记为未读
            sysUserFriendService.insertHistory(new MesMessage(0, user.getUserId().intValue(),mess.getSendId(),mess.getMessage(),0,null));
            //存储在redis
          //  redisTemplate.opsForHash().put(String.valueOf(user.getUserId()),String.valueOf(mess.getSendId()),);

            //发生消息
            webSocketServer.session.getBasicRemote().sendText(data);

        }

    }

    @OnClose
    //连接关闭时调用
    public void onClose(Session session) {
        onlineUsers.remove(user.getUsername());
        System.out.println("-------------"+user.getUsername()+"退出聊天室-----------");


    }


}